package com.warren.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.warren.annotation.ControllerEndpoint;
import com.warren.auth.entity.JwtUser;
import com.warren.handler.BusinessException;
import com.warren.response.Result;
import com.warren.response.ResultCode;
import com.warren.system.entity.User;
import com.warren.system.service.AliOssService;
import com.warren.system.service.UserService;
import com.warren.system.vo.UserEditVO;
import com.warren.system.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.security.util.Password;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author warren
 * @since 2021-03-21
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(value = "系统用户管理" ,tags="系统用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @RequestMapping(value = "/findUserList", method = RequestMethod.GET)
    @ApiOperation(value = "用户列表",notes = "分页查询所有用户信息")
    public Result findUserList(@RequestParam(required = true,defaultValue = "1")Integer current,
                               @RequestParam(required = true,defaultValue = "6")Integer size){
        Page<User> page = new Page<>(current, size);
        Page<User> userPage = userService.page(page);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records",records);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个用户",notes="通过id查询对应的用户信息")
    public Result getUserById(@PathVariable("id") long id){
        User user = userService.getById(id);
        if (null != user){
            return Result.ok().data("user",user);
        }else {
            throw new BusinessException(ResultCode.USER_NOT_FOUND_EXCEPTION.getCode(),
                    ResultCode.USER_NOT_FOUND_EXCEPTION.getMessage());
        }
    }

    @PostMapping("/findUserPage")
    @ApiOperation(value = "根据用户条件进行分页查询",notes = "根据用户的部门，账号，邮箱，性别，别名查询")
    public Result findUserPage(@RequestParam(required = true,defaultValue = "1") Integer current,
                               @RequestParam(required = true,defaultValue = "6")Integer size,
                               @RequestBody UserVO userVO){
        //用户进行分页，泛型中注入的就是用户实体类
        Page<User> page = new Page<>(current,size);
        //单表的时候，这个方法很好用
        QueryWrapper<User> wrapper = getWrapper(userVO);
        IPage<User> userPage = userService.findUserPage(page, wrapper);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        return Result.ok().data("total",total).data("records",records);
    }

    @ApiOperation(value = "添加用户",notes = "添加用户信息")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user){
        try {
            userService.addUser(user);
            return Result.ok();
        } catch (Exception e) {
            log.info("添加用户失败",e);
            return Result.error();
        }
    }

    @ApiOperation(value = "导出用户信息",notes = "导出用户信息到excel")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, @RequestBody(required =
            false)UserVO userVO)throws IOException{
        QueryWrapper<User> wrapper = getWrapper(userVO);
        List<User> users = userService.list(wrapper);
        userService.exportUserExcel(response,users);
    }

    @ApiOperation(value = "编辑用户",notes = "获取用户的详情，编辑用户的信息")
    @GetMapping("/edit/{id}")
    public Result edit(@PathVariable Long id)throws BusinessException{
        UserEditVO userVO = userService.edit(id);
        return Result.ok().data("uservo",userVO);
    }

    @ApiOperation(value = "更新用户",notes = "更新用户信息")
    @PutMapping("/update/{id}")
    public Result updateUser(@PathVariable Long id, @RequestBody  @Validated UserEditVO userEditVO)throws BusinessException{
        System.out.println(userEditVO);
        userService.updateUser(id,userEditVO);
        return Result.ok().message("更新用户成功");
    }

    @ApiOperation(value = "删除用户",notes = "删除用户信息，根据用户ID")
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Long id)throws BusinessException{
        //注意这里是逻辑删除
        userService.deleteById(id);
        return Result.ok().message("删除成功");
    }

    @ApiOperation(value = "用户状态",notes = "禁用和启用这两种状态")
    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id,@PathVariable Boolean status)throws BusinessException{
        userService.updateStatus(id,status);
        return Result.ok().message("更新状态成功");
    }

    @ControllerEndpoint(exceptionMessage = "修改密码失败",operation = "修改用户密码")
    @ApiOperation(value = "修改用户密码",notes = "根据用户名修改")
    @PostMapping("/updateUserPassword")
    public Result updateUserPassword(String oldPassword,String newPassword){
        User updateUser = new User();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser userInfo = (JwtUser) authentication.getPrincipal();
        if (passwordEncoder.matches(oldPassword,userInfo.getPassword())){
            updateUser.setPassword(passwordEncoder.encode(newPassword));
        }else {
            return Result.error(ResultCode.USER_CREDENTIALS_ERROR);
        }

        try {
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("username",userInfo.getUsername());
            userService.update(updateUser,userUpdateWrapper);
            return Result.ok().message("修改成功");
        } catch (Exception e) {
            return Result.error().message("修改失败");
        }
    }


    private QueryWrapper<User> getWrapper(UserVO userVO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userVO != null){
            if (!StringUtils.isEmpty(userVO.getDepartmentId())){
                queryWrapper.eq("department_id",userVO.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVO.getUsername())){
                queryWrapper.eq("username",userVO.getUsername());
            }
            if (!StringUtils.isEmpty(userVO.getSex())){
                queryWrapper.eq("sex",userVO.getSex());
            }
            if (!StringUtils.isEmpty(userVO.getNickname())){
                queryWrapper.eq("nickname",userVO.getNickname());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())){
                queryWrapper.eq("email",userVO.getEmail());
            }
            queryWrapper.eq("deleted",0);
        }
        return queryWrapper;
    }
}

